import { login } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { getRole } from '@/api/user'
import Cookie from 'js-cookie'

const user = {
  state: {
    token: getToken(),
    name: '',
    id: '',
    companyName:'',
    roles: [],
    user:{}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_ID: (state, id) => {
      state.id = id
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_COMPANYNAME: (state,comName)=>{
      state.companyName = comName
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_USER:(state, user)=>{
      state.user = user
    }
  },

  actions: {
    // 用户名登录
    login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        login(username, userInfo.password).then(data => {
          // const { token, id } = data
          commit('SET_NAME', data.data.account.accountName)
          commit('SET_COMPANYNAME', data.data.account.companyName)
          commit('SET_ROLES', data.data.roles)
          Cookie.set('user', data.data.account)
          commit('SET_USER', data.data.account)
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getRole(JSON.parse(Cookie.get('user')).id).then(data => {
          const { account,roles } = data.data;

          if (!account) {
            reject('Verification failed, please Login again.')
          }
          // const { username, roles } = account
          commit('SET_ROLES', roles)

          resolve({ roles: roles ,account:account})
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ dispatch, state }) {
      return new Promise((resolve, reject) => {
        dispatch('FedLogOut')
        removeToken()
        resolve(state)
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_ID', '')
        commit('SET_NAME', '')
        commit('SET_ROLES', [])
        Cookie.remove('id')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
